from Autotests.LocalMachine.Pages.BasePage import BaseWebPage
from Autotests.LocalMachine.Controls.BaseControl import WebFindKey
from Autotests.LocalMachine.UiObjectsMap.AirClient import MainFrame, Options
from Autotests.LocalMachine.Controls import *
from Autotests.WebDriver import DRIVER
from urlparse import parse_qs


class WebMainPage(BaseWebPage):
    def __init__(self):
        super(WebMainPage, self).__init__(MainFrame.frame)
        self._buttonLsvSetup = WebButton(MainFrame.btnLSVSetup)
        self._buttonScheduleSetup = WebButton(MainFrame.btnScheduleSetup)
        self._buttonManageDevices = WebButton(MainFrame.btnManageDevices)
        self._buttonAssignToAccount = WebButton(MainFrame.btnAssignToAccount)
        self._buttonBuyNow = WebButton(MainFrame.btnBuyNow)
        self._trialLabel = WebLabel(MainFrame.trialLabel)

    def goToHomeLocation(self):
        super(WebMainPage, self).goToHomeLocation()

    def goToLsvSettings(self):
        self.goToHomeLocation()
        self._buttonLsvSetup.click()

    def isLsvTabVisible(self):
        return BaseWebControl(Options.LocalSpeedKick.frame).isVisible()

    def goToSceduleSettings(self):
        self.goToHomeLocation()
        self._buttonScheduleSetup.click()

    def isScheduleTabVisible(self):
        return BaseWebControl(Options.Schedule.frame).isVisible()

    def goToManageDevicesPage(self):
        self.goToHomeLocation()
        if self._buttonAssignToAccount.isExists(2):
            self._buttonManageDevices.click()
            return False
        else:
            self._buttonManageDevices.click()
            DRIVER().switch_to_window(DRIVER().window_handles[-1])
            return True

    def goToAssignToAccountPage(self):
        self.goToHomeLocation()
        if self._buttonAssignToAccount.isExists(2):
            self._buttonAssignToAccount.click()
            return True
        else:
            return False

    def isTeamViewerVisible(self):
        teamViewerDialog = BaseWebControl(MainFrame.frameTeamViewer)
        return teamViewerDialog.isExists() and teamViewerDialog.isVisible()

    def goToBuyNowPage(self):
        self.goToHomeLocation()
        if self._buttonBuyNow.isExists(2):
            self._buttonBuyNow.click()
            DRIVER().switch_to_window(DRIVER().window_handles[-1])
            return True
        else:
            return False

    def isBuyNowPageActive(self):
        return 'buy' in DRIVER().current_url

    def isAllDevicesPageActive(self):
        return 'login' in DRIVER().current_url

    @BaseWebPage.getter
    def buildVersion(self):
        feedBackLink = WebButton(MainFrame.feedBackLink)
        return parse_qs(feedBackLink.get_attribute('href'))['body'][0].replace('Version: ', '')